package com.m3958.firstgwt.server.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.MappedSuperclass;

import com.m3958.firstgwt.server.types.HasToJson;
import com.m3958.firstgwt.server.types.TreeModel;
import com.m3958.firstgwt.shared.type.SmartConstants;

@MappedSuperclass
public abstract class BaseTreeModel<T extends BaseTreeModel<T>> extends HasSiteIdModel<T> implements TreeModel<T>,Serializable,HasToJson {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected int childrenNum;
	
	protected String parentIds;
	
	protected int persistedParentId = SmartConstants.NONE_EXIST_MODEL_ID;
	
	@Override
	public boolean isFolder() {
		return childrenNum > 0;
	}
	
	protected  String getParentPath(TreeModel<T> other) {
		String s = ",";
		TreeModel<T> cu = other;
		while(cu != null){
			s += cu.getId() + ",";
			cu = cu.getParent();
		}
		return s;
	}
	
	@Override
	public boolean addChildren(TreeModel<T> bm) {
		if(!getChildren().contains(bm)){
			getChildren().add((T) bm);
			return true;
		}
		return false;
	}
	
	
	public List<T> getSiblings(){
		List<T> sbs = new ArrayList<T>();
		if(getParent()!=null){
			for(TreeModel<T> s:getParent().getChildren()){
				if( s != this && !((Section) s).getHidden()){
					sbs.add((T) s);
				}
			}
		}else{
			if(getSite(siteId) == null)return sbs;
			for(BaseTreeModel<T> s : getSite(siteId).getTreeTops(this)){
				if(s!=this){
					sbs.add((T) s);
				}
			}
		}
		return sbs;
	}
	
	protected void setParentExtra(){
		if(getParent() != null){
			this.parentIds = getParentPath(getParent());
			this.persistedParentId = getParent().getId();
		}else{
			this.parentIds = "";
			this.persistedParentId = SmartConstants.NONE_EXIST_MODEL_ID;
		}
	}

	@Override
	public boolean removeChildren(TreeModel<T> bm) {
		if(getChildren().contains(bm)){
			getChildren().remove(bm);
			return true;
		}
		return false;
	}
	
	@Override
	public int getParentId() {
		return persistedParentId;
	}


	public int getChildrenNum() {
		return childrenNum;
	}
	

	@Override
	public void setChildrenNum(int childrenNum) {
		this.childrenNum = childrenNum;
	}
	
	public String getParentIds() {
		return parentIds;
	}

	public void setPersistedParentId(int persistedParentId) {
		this.persistedParentId = persistedParentId;
	}

}
